package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.LoginResultDTO;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.AuthFailDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-03-22
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public LoginResultDTO login(AppLoginDto dto) {
        // 先判断是否传递了手机号和密码
        // 是，则校验手机号和密码，校验通过，生成token 返回
        // 否，直接生成token 返回
        if(StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())){
            // 根据手机号查询用户
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser userDB = this.getOne(queryWrapper);
            if(userDB == null){
                throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
            }
            String passwordDB = userDB.getPassword();
            String passwordInput = dto.getPassword();
            boolean matches = passwordEncoder.matches(passwordInput, passwordDB);
            if(!matches){
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 生成token
            String token = JwtUtils.generateTokenExpireInMinutes(userDB.getId(), 120);
            return new LoginResultDTO(BeanHelper.copyProperties(userDB, AdUserDto.class), token);
        }else{
            // 匿名登陆
            String token = JwtUtils.generateTokenExpireInMinutes(-1, 120);
            return new LoginResultDTO(null, token);
        }
    }

    @Override
    public void updateToWemdiaUser(Integer userId) {
        ApUser toBeUpdate = new ApUser();
        toBeUpdate.setId(userId);
        toBeUpdate.setFlag(1);//TODO 枚举
        toBeUpdate.setIsIdentityAuthentication(true);
        toBeUpdate.setIsCertification(true);
        this.updateById(toBeUpdate);
    }
}
